<?php
namespace app\v2\controller;

use think\Db,
    think\Request,
    app\v2\model\ScoreLog,
    \app\v2\validate\TdPreloanApply;
    /**
 * 西瓜处理类
 */
class Watermelon extends Base
{
    protected $options = array();
    protected $user = array();
    protected $channel = 1006;
    public function  __construct()
    {
        parent::__construct();
        // $this->user = session('user');
        $this->TondunModel =  model('v2/Watermelon');
        $this->Score =  model('v2/Score');
        if('127.0.0.1' == $_SERVER['SERVER_ADDR'] ){
            DEFINE('IS_TEST',true);
        }else{
            DEFINE('IS_TEST',false);
        }
    }

    /**
     * 生成西瓜报告
     */
    public function creditReport(array &$arr){

        $uid = $arr['uid'];
        unset($arr['uid']);
        $report =  Db::name('user_info')->where(['uid'=>$uid])->value('report_id');
        //一个月更新一次
        $apply_time = Db::name('td_preloan_report')->where(['uid'=>$uid])->value('apply_time');

        if($report && ($apply_time > strtotime('-1 month'))){
            return resultArray(['error' =>"您已查询过征信，无需重复查询"]);
        }
        $data = $arr;
        $data['channel'] = $this->channel;
        $data['userId'] = date('YmdHis',time()).$uid;
        //表单验证  用td的表单验证
        $validate = new TdPreloanApply();
        if (!$validate->check($data)) {
          return resultArray(['error' => $validate->getError()]);
        }
        /*$accountdata=array();
        //判断是否第一次查询免费  查的到就不是第一次
        $isfrist=Db::name('td_account')->where('uid',$uid)->find();
        if($isfrist['first_times']){
            $accountdata["last_time"] = time();
            $accountdata["last_time_str"] = date('Y-m-d H:i:s',time());
            if($isfrist['total_times'] > 5){  // 定义查询最大次数为5次
              return resultArray(['error'=>'查询次数过多']);
            }
            $accountdata['total_times']=$isfrist['total_times']+1;
            $score=0;  //查询报告扣的金额  第一次免费
        }else{
            $score=0;  //查询报告扣的金额  第一次免费
            $accountdata['uid']=$uid;
            $accountdata["create_time"] = time();
            $accountdata["create_time_str"] = date('Y-m-d H:i:s',time());
            $accountdata["last_time"] = time();
            $accountdata["last_time_str"] = date('Y-m-d H:i:s',time());
            $accountdata['total_times']=1;
            $accountdata['first_times']=1;
        }*/
        /* 调用 [贷前审核] 接口 返回一个状态和一个申请风险报告编号  IS_TEST判断是否式本地数据*/
        $result = preloan_apply($data);
        $param['name'] = 'name';
        $param['mobileNo'] = $data['phone'];
        $param['idCardNo'] = $data['idnumber'];
        $param['channel'] = $this->channel;
        $re = preloan_report_risk($param);//获取风险报告
        if($result['code'] == 200 && $re['code'] == 200){
            //添加td_preloan_apply表
            $fromList = array(
                'name'            => $data['name'],
                'id_number'       => $data['idnumber'],
                'mobile'          => $data['phone'],
                'report_id'       => $result['data']['label'],
                'loan_term_unit'  => 'DAY',
                'uid'             => $uid,
                'create_time'     => time(),
                'create_time_str' => date('Y-m-d H:i:s',time()),
                'application_id'  => $result['data']['outUniqueId'],
            );
            //添加td_preloan_report表;
            $add=array(
                //注  这个可以用strict(true)
                //$id = Db::name('td_preloan_apply')->strict(true)->insert($data);
                //扣钱成功之后 将数据存入查询记录中  要跳到记录中看报告
                'report_id'       => $result['data']['label'],
                "uniacid"         => 2,
                'uid'             => $uid,
                'create_time'     => time(),
                'create_time_str' => date('Y-m-d H:i:s',time()),
                'application_id'  => $re['data']['outUniqueId'],
                'final_decision'  => $re['data']['desc'],
                'final_level'     => $re['data']['quotaValue'],
                'status_code'     => $re['data']['rspCode'],
                'return_message'  => $re['data']['rspMsg'],
                'return_redis'    => $re['data']['redis'],
                'apply_time'      => time(),
                'report_time'     => time(),
                'status'          => 1,
            );
            Db::startTrans();
            try{
                Db::name('user_info')->where('uid',$uid)->update(array('report_id'=>$result['data']['label']));  
                
                Db::name('td_preloan_apply')->insert($fromList);
                //扣钱成功后  往统计加数据
                /*if($isfrist){
                    Db::name('td_account')->where('uid',$uid)->update($accountdata);
                }else{
                    Db::name('td_account')->insert($accountdata);
                }*/
                Db::name('td_preloan_report')->insert($add);
                #写日志
                $scoreLogModel = new ScoreLog();
                //$scoreLogModel->addlog($uid,$recored=0,$score,$opretion="setDec",$logid=1,$type="查征信");
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return resultArray(['error'=>'操作失败']);
            }
            return resultArray(['data'=>$result['data']['label']]);
        }else{
            return resultArray(['error'=>$result['error']]);
        }
    }

    /**
     * 查询报告列表
     */
    public function reportList(Request $request){
        $arr=$this->isLogin();
        if(!$arr['status']){
           return resultArray(['error' =>$arr['info']]);
        }        
        $uid = $arr['uid'];

        $page = $request->post('page',"1");
        $count = $request->post('count',"3");

        $reportList = Db::name('td_preloan_report')->alias('r')
                        ->join('td_preloan_apply a','r.report_id = a.report_id','LEFT')
                        ->field("r.id,r.uid,r.status,r.report_id,r.application_id,r.create_time_str,a.name")
                        ->where(array('r.uid'=>$uid))
                        ->page($page,$count)
                        ->order('r.id desc')
                        ->select();
        $count = Db::name('td_preloan_report')->alias('r')
                        ->join('td_preloan_apply a','r.report_id = a.report_id','LEFT')
                        ->where(array('r.uid'=>$uid))
                        ->count(); 
        $data["list"] =  $reportList;                      
        $data["count"] =  $count; 
        if($reportList){
          return resultArray(['data'=>$data]);
        }else{
          return resultArray(['error'=>"没有获取到数据"]);
        }
        
    }
    /**
     * 查询同盾是否成功生成报告
     */
    public function refresh(Request $request){
        $arr=$this->isLogin();
        if(!$arr['status']){
            return resultArray(['error' =>$arr['info']]);
        }
        $uid = $arr['uid'];
        $param['label'] = $request->post('report_id');
        $param['channel'] = $this->channel;
        $param['uid'] = $uid;
        $refresh = $this->TondunModel->refresh($param);
        //发放奖励
        //model('Reward','logic')->rewardCom(1,$uid);
        if(!$refresh){
            return resultArray(['error' => $this->TondunModel->getError()]); 
        }else{
          return resultArray(['data'=>$refresh]); 
        }
    }
    /**
     * 贷前申请 - 查询报告详情
     * @author llj <llj465705075@gmail.com>
     * @time(2016年12月11日22:16:04)
     * http://local.yifu.com/cvi.php?s=/tong_dun/report/report_id/ER2016121123314012494030.html
     */
    public function report(Request $request)
    {
        $arr=$this->isLogin();
        if(!$arr['status']){
           return resultArray(['error' =>$arr['info']]);
        }        
        $param['uid'] = $arr['uid'];
        $param['label'] = $request->post("report_id","");
        $param['channel'] = $this->channel;
        $result=$this->TondunModel->detail($param);
        if(!$result){
            return resultArray(['error' => $this->TondunModel->getError()]);
        }
        return resultArray(['data' => $result]);
    }

    /**
     * 贷前申请 - 页面
     * @author llj <llj465705075@gmail.com>
     * @time(2016年12月11日22:16:04)
     */
    public function preloanCheck()
    {
        $arr=$this->isLogin();
        if(!$arr['status']){
            return resultArray(['error' =>$arr['info']]);
        }
        //$uid = '1131';//测试
        $uid=$arr['uid'];
        $data = Db::name('td_account')->field('total_times')->where('uid',$uid)->find();
        //获取系统配置单价
        $res=$this->systemConfigModel->getSysConfigList();
        if($res['CREDIT_UNIT_PRICE']<1){
            $data['price']=10;
        }else{
            $data['price']=$res['CREDIT_UNIT_PRICE'];
        }
        if(!$data){
            $data['total_times']=0;     //历史查询次数
        }
        //获取用户余额
        $data['score']=$this->Score->balance($uid);
        return resultArray(['data' => $data]);
    }
}